package com.lonty.intelligence.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author 陈璇
 * @Date 2020/4/14 11:35
 * @Version 1.0
 **/
public class WeChatUtil {

    private final static String AppID = "wxb488b4fe81f89807";

    private final static String AppSecret = "6e0aa9f5cb62bb715d38cab9d8854aaa";

    private final static String grant_type = "authorization_code";

    //获取openid url
    private final static String WX_OPEN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    //获取access_token url
    private final static String WX_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    //获取用户信息 url
    private final static String WX_USERINFO_URL = "https://api.weixin.qq.com/sns/userinfo";

    public static String weChatLogin(String code) throws Exception {
        //获取openid
        StringBuffer loginUrl = new StringBuffer();
        loginUrl.append(WX_OPEN_URL).append("?appid=")
                .append(AppID).append("&secret=")
                .append(AppSecret).append("&js_code=").append(code)
                .append("&grant_type=").append(grant_type);
        System.out.println("获取openid url:" + loginUrl.toString());
        String loginRet = httpRequest(loginUrl.toString(),"GET",null);
        System.out.println("获取openid返回信息:" + loginRet);
        JSONObject grantObj = JSON.parseObject(loginRet);
        String errCode = grantObj.getString("errcode");
        if (!StringUtils.isEmpty(errCode))
        {
            return null;
        }
        String openid = grantObj.getString("openid");
        return openid;
    }

    //处理http请求  requestUrl为请求地址  requestMethod请求方式，值为"GET"或"POST"
    public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
        StringBuffer buffer=null;
        try{
            URL url = new URL(requestUrl);
            HttpURLConnection conn=(HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod(requestMethod);
            conn.connect();
            //往服务器端写内容 也就是发起http请求需要带的参数
            if(null != outputStr){
                OutputStream os=conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }

            //读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr=new InputStreamReader(is,"utf-8");
            BufferedReader br=new BufferedReader(isr);
            buffer=new StringBuffer();
            String line = null;
            while((line=br.readLine())!=null){
                buffer.append(line);
            }
            System.out.println("[weixin]: do get request({}), and get response({})." + url + "," + "," + buffer.toString());
        }catch(Exception e){
            e.printStackTrace();
        }
        return buffer.toString();
    }

}
